package com.atguigu.thread;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class ProductiveConsumptionDemo {

    public static void main(String[] args){
        //创建有界生产队列，当生产者速度较快，消费者速度较慢时生产会被阻塞，等待消费
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);

        // 创建无界队列
        // LinkedBlockingQueue<String> queue1 = new LinkedBlockingQueue<>();

        //创建一个状态
        AtomicBoolean status = new AtomicBoolean(true);

        // 创建生产者线程
        new Thread(()->{
            try {
                int count = 0;
                while(status.get()) {
                    // 设置随机时间
                    // int[] time = {1000,2000,3000,4000,5000};
                    // Random random = new Random();
                    // int randomIndex = random.nextInt(time.length);
                    // int randomTime = time[randomIndex];
                    int randomTime = 3000;

                    System.out.println("开始做馒头……");
                    Thread.sleep(randomTime);
                    boolean mono = queue.offer("馒头");
                    if (!mono){
                        System.out.println("馒头已经满了，快去吃吧！");
                        Thread.sleep(10000);
                    }else {
                        System.out.println("馒头做好了，（已经做了"+(++count)+"个馒头)");
                    }
                }
                System.out.println("感谢光临，顾客慢走");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"生产者").start();

        // 创建消费者线程
        new Thread(()->{
            try {
                int count = 0;
                while(status.get()) {
                    //设置随机时间
                    // int[] time = {1000,2000,3000,4000,5000};
                    // Random random = new Random();
                    // int randomIndex = random.nextInt(time.length);
                    // int randomTime = time[randomIndex];
                    int randomTime = 5000;

                    System.out.println("》看看有没有馒头");
                    String mono = queue.poll(2,TimeUnit.SECONDS);  //如果没有馒头等待两秒
                    if(mono != null){
                        System.out.println("》开始吃馒头……");
                        Thread.sleep(randomTime);
                        System.out.println("》吃了一个"+mono+"！已经吃了"+(++count)+"个馒头");
                    }else {
                        System.out.println("》怎么没馒头了，快去做！");
                    }
                    if(count==10){
                        status.set(false);
                        System.out.println("》我已经吃饱了，谢谢");
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        },"消费者").start();
    }
}
